﻿using System;
using System.Configuration;
using System.Data.Common;
using System.IO;
using System.Web;
using System.Xml.XPath;
using Songhay.Data;
using Songhay.Data.Common;
using Songhay.Xml;

namespace Songhay.Web
{
    public partial class DataActivtyServer : HttpApplication
    {
        /// <summary>
        /// Handles all postbacks for this application.
        /// </summary>
        /// <param name="ReqBag">
        /// The <see cref="Songhay.Web.RequestBag"/>.
        /// </param>
        public static string HandlePostBack(HttpContext Context)
        {
            RequestBag request = new RequestBag(Context);

            string s = null;

            XPathDocument d = null;

            try
            {
                if(string.IsNullOrEmpty(request.DataConnectionId)) throw new ArgumentException("The Data Connection ID associated with the Request was not found.");

                //Collect DBMS metadata:
                DataAccessItem dbInfo = DataActivtyServer._dbmsMeta.GetDataAccessItem(request.DataConnectionId);
                ICommandHandler dataCmd = DataActivtyServer._dataManagers[request.DataConnectionId];
                string connectionString = dbInfo.Connection[0].ConnectionString;
                string providerInvariantName = dbInfo.Connection[0].InvariantProviderName;

                //Find XSL file associated with Request:
                NameValuePair xslInfo = dbInfo.GetNameValuePair(request.Command);
                if(xslInfo == null) throw new ConfigurationErrorsException(string.Format("The XSL file ID, “{0},” associated with the Request was not found.", request.Command));
                string xslpath = Context.Server.MapPath(xslInfo.Value);
                if(!File.Exists(xslpath)) throw new ConfigurationErrorsException(string.Format("XSL file “{0}” not found.", xslpath));

                using(DbConnection cnn = CommonDbms.GetConnection(providerInvariantName, connectionString))
                {
                    cnn.Open();

                    if(!string.IsNullOrEmpty(request.DataId))
                    {
                        //Handle GET (data item) Request:
                        DataCommandInput<string> input = new DataCommandInput<string>();
                        input.CommandName = request.Command;
                        input.DataConnection = cnn;
                        input.Message = request.DataId;
                        d = dataCmd.DoCommand<string>(input);
                    }
                    else if(string.IsNullOrEmpty(request.XmlPostData))
                    {
                        //Handle GET (display) Request:
                        DataCommandInput input = new DataCommandInput();
                        input.CommandName = request.Command;
                        input.DataConnection = cnn;
                        d = dataCmd.DoCommand(input);
                    }
                    else
                    {
                        //Handle POST Request:
                        DataCommandInput<string> input = new DataCommandInput<string>();
                        input.CommandName = request.Command;
                        input.DataConnection = cnn;
                        input.Message = request.XmlPostData;
                        d = dataCmd.DoCommand<string>(input);
                    }

                    s = XmlUtility.LoadXslTransform(xslpath, request.Command, d);
                }
            }
            catch(Exception ex)
            {
                s = XmlUtility.GetInternalMessage(
                    string.Format("Exception for {0}", request.Command),
                    new string[] { XmlUtility.ExpandSpecialChars(ex.Message),
                    string.Format("Identifier: {0}",request.DataId),
                    string.Format("Data Connection ID: {0}",request.DataConnectionId),
                    string.Format("Server Command: {0}",request.Command),
                    string.Format("XML POST: {0}",request.XmlPostData),
                    XmlUtility.ExpandSpecialChars(ex.StackTrace)});

                s = XmlUtility.LoadXslTransform(DataActivtyServer._clientXsl, string.Empty, s);
            }

            return XmlUtility.StripNamespaces(s);
        }
    }
}